//
//  ShopCarViewController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/5/30.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "ShopCarViewController.h"
#import "homeCollectionViewCell.h"
#import "ShopCarLastView.h"
#import "ShopCarHeaderView.h"
#import "ProductInfo.h"
#import "ShopCarTableViewCell.h"
#import "CarConfirmOrderController.h"
#import "LogInViewController.h"

#define MAR_WIDTH 5

static NSString *const reuseIdentifier = @"shopCarTableViewCell";

@interface ShopCarViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,ShopCarHeaderViewDelegate,UITableViewDataSource,UITableViewDelegate,didClickDeleteButtonDelegate>
{
    MBProgressHUD *progressHUD;
    
    //全选按钮
    UIButton *selectAll;
    
    //是否全选
    BOOL isSelect;
    
    //已选的商品集合
    
    UILabel *priceLabel;
    
    UIButton *leftButton;
    
    NSMutableArray *numbersArray;
}

@property (nonatomic,strong)UICollectionView *collectionView;

@property (nonatomic,strong)NSMutableArray *productsArray;

@property (nonatomic,strong)UITableView *shopCarTableView;

@property (nonatomic,strong)ShopCarLastView *lastView;

@property (nonatomic,strong)NSMutableArray *selectedButton;

@property (nonatomic,strong) NSMutableArray *selectGoods;

@end

@implementation ShopCarViewController

static NSString * const firstReuseIdentifier =  @"firstCollectionView";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"购物车";
    //    self.selectGoods = [NSMutableArray array];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //    static dispatch_once_t onceToken;
    //    dispatch_once(&onceToken, ^{
    progressHUD = [MBProgressHUD loadingInformationToView];
    [self.view addSubview:progressHUD];
    //    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self shopCartDatasources];
    });
    
}

- (void)dealloc {
    NSLog(@"%s",__func__);
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSLog(@"%s",__func__);
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.productsArray removeAllObjects];
    [self.shopCarTableView removeFromSuperview];
    [self.lastView removeFromSuperview];
    [self.collectionView removeFromSuperview];
    //    [self.selectGoods removeAllObjects];
    [progressHUD hide:YES];
    if (!progressHUD.removeFromSuperViewOnHide) {
        [progressHUD removeFromSuperview];
    }
}

#pragma mark 数据请求
- (void)shopCartDatasources {
    
    if (!USERNAME) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您尚未登录用户" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LogInViewController *accountVC = [[LogInViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:accountVC];
            [self presentViewController:nav animated:YES completion:nil];
        }];
        [alert addAction:SettingAction];
        
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self addMainCollectionView];
        }];
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    
    
    [self.productsArray removeAllObjects];
    [self.shopCarTableView removeFromSuperview];
    [self.lastView removeFromSuperview];
    [self.selectGoods removeAllObjects];
    
    NSDictionary *params = @{
                             @"username":USERNAME
                             };
    
    NSString *string = @"/api/Cart/lists";
    
    //    NSString *string = @"http://www.ylgw8.com/AppShopOrder/GwcList";
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:string completeBlock:^(id object) {
            
            if (!JudgeBackDataCode) {
                [self addMainCollectionView];
                return;
            }
            
            NSDictionary *dict = object[@"data"];
            NSArray *arrayM = dict[@"list"];
            
            [progressHUD hide:YES];
            if (progressHUD.removeFromSuperViewOnHide) {
                [progressHUD removeFromSuperview];
            }
            
            for (int i = 0; i < arrayM.count; i++) {
                NSDictionary *infoDict = arrayM[i];
                ProductInfo *prodict = [ProductInfo newsWithDict:infoDict];
                [self.productsArray addObject:prodict];
            }
            
            [self.shopCarTableView.mj_header endRefreshing];
            
            [self addShopCarTableView];
            
            [self.shopCarTableView reloadData];
        }];
    });
}

- (void)deleteDatasources:(NSString *)replaceID {
    
    [progressHUD hide:YES];
    
    NSDictionary *params = @{
                             @"username":USERNAME,
                             @"cart_id":replaceID
                             };
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[NetWorkSharedTools sharedNetWorkTools] GetObjectWithURLDict:params AndMenthodName:@"/api/Cart/deleteById" completeBlock:^(id object) {
            
            /**
             ShopCarViewController.m:155	{
             data = "";
             info = "\U5220\U9664\U6210\U529f";
             status = 1;
             }
             */
            NSDictionary *message = [object objectForKey:@"message"];
            dispatch_async(dispatch_get_main_queue(), ^{
                MBProgressHUD *hud = [MBProgressHUD showMessage:[message objectForKey:@"view"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
                [self countPrice];
                [self.view addSubview:hud];
            });
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                if ([[NSString stringWithFormat:@"%@",object[@"code"]] isEqual:@"1"]) {
                    
                    for (int i = 0; i < self.selectGoods.count; i++) {
                        ProductInfo *model = self.selectGoods[i];
                        if ([model.id isEqualToString:replaceID]) {
                            [self.selectGoods removeObjectAtIndex:i];
                        } else {
                            break;
                        }
                    }
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        static dispatch_once_t onceToken;
                        dispatch_once(&onceToken, ^{
                            progressHUD = [MBProgressHUD loadingInformationToView];
                            [self.view addSubview:progressHUD];
                        });
                        
                        [self.shopCarTableView removeFromSuperview];
                        [self.lastView removeFromSuperview];
                    });
                    
                    [self.productsArray removeAllObjects];
                    
                    [self.shopCarTableView.mj_header beginRefreshing];
                }
                
            });
        }];
    });
}

- (void)SetUpShopCarEditNumber:(NSDictionary *)params {
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Cart/editNum" completeBlock:^(id object) {
        NSLog(@"%@",object);
    }];
}

#pragma mark ------ 添加控件

- (void)addShopCarTableView {
    
    isSelect = NO;
    
    CGFloat Navheight = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    
    CGFloat tabBarHeigjt = CGRectGetHeight(self.tabBarController.tabBar.frame);
    
    CGFloat tableViewHeight = HEIGHT - Navheight - tabBarHeigjt-49;
    if (_isPushCar) {
        tableViewHeight = HEIGHT - Navheight - tabBarHeigjt;
    }
    self.shopCarTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0 , WIDTH, tableViewHeight) style:UITableViewStylePlain];
    self.shopCarTableView.tableFooterView = [[UIView alloc] init];
    self.shopCarTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.shopCarTableView.delegate = self;
    self.shopCarTableView.dataSource = self;
    self.shopCarTableView.backgroundColor = RGB(234, 234, 234);
    self.shopCarTableView.mj_header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(shopCartDatasources)];
    [self.view addSubview:self.shopCarTableView];
    
    ShopCarLastView *lastView = [[ShopCarLastView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.shopCarTableView.frame), WIDTH, 49)];
    //    lastView.backgroundColor = [UIColor grayColor];
    selectAll = lastView.chooseButton;
    selectAll.selected = NO;
    [selectAll addTarget:self action:@selector(didClickChooseSelectedAllButton:) forControlEvents:UIControlEventTouchUpInside];
    
    priceLabel = lastView.priceLabel;
    priceLabel.text = [NSString stringWithFormat:@"￥0.00"];
    self.lastView = lastView;
    
    [lastView.accountButton addTarget:self action:@selector(didClickGoPayBttton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:lastView];
}

- (void)addMainCollectionView
{
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
    
    flowlayout.minimumLineSpacing = 0;
    flowlayout.minimumInteritemSpacing = 0;
    flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    CGFloat height = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    CGFloat tabBarHeight = CGRectGetHeight(self.tabBarController.tabBar.frame);
    UICollectionView *homeCollectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,WIDTH, HEIGHT-height-tabBarHeight) collectionViewLayout:flowlayout];
    self.collectionView = homeCollectView;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    //    _collectionView.backgroundColor = BACKGROUND_COLOR;
    [self.view addSubview:_collectionView];
    
    //注册cell
    [self.collectionView registerClass:[homeCollectionViewCell class] forCellWithReuseIdentifier:firstReuseIdentifier];
    
    //    注册表头
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"shopCarHeader"];
    
}

#pragma mark 计算价格逻辑和全选逻辑

/**
 *  计算已选中商品金额
 */
-(void)countPrice
{
    double totlePrice = 0.0;
    
    for (ProductInfo *model in self.selectGoods) {
        
        double price = [model.jiage doubleValue];
        
        totlePrice += price * model.nums;
    }
    priceLabel.text = [NSString stringWithFormat:@"￥%.2f",totlePrice];
}

- (void)didClickChooseSelectedAllButton:(UIButton *)selectedButton {
    //点击全选时,把之前已选择的全部删除
    [self.selectGoods removeAllObjects];
    
    //    selectedButton.selected = !selectedButton.selected;
    isSelect = selectedButton.selected;
    if (isSelect) {
        
        for (ProductInfo *model in self.productsArray) {
            
            [self.selectGoods addObject:model];
        }
    }
    else
    {
        [self.selectGoods removeAllObjects];
    }
    
    [self.shopCarTableView reloadData];
    [self countPrice];
}

/**
 *  结算按钮
 */
- (void)didClickGoPayBttton:(UIButton *)accountButton {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        //        for (UIButton *button in self.selectedButton) {
        //            if (button.selected) {
        //                ProductInfo *product = self.productsArray[button.tag];
        //                [selectGoods addObject:product];
        //            }
        //        }
        
        if (!self.selectGoods.count) {
            dispatch_async(dispatch_get_main_queue(), ^{
                MBProgressHUD *hud = [MBProgressHUD showMessage:@"请选择商品" toView:self.view dimBackground:NO AndCompleteBlock:nil];
                [self.view addSubview:hud];
            });
        } else {
            NSLog(@"%@",self.selectGoods);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                progressHUD = [MBProgressHUD show:self.view andMessage:@"正在创建订单"];
                [self.view addSubview:progressHUD];
            });
            
            for (ProductInfo *productInfo in self.selectGoods) {
                NSDictionary *params = @{
                                         @"username":USERNAME,
                                         @"cart_id":productInfo.id,
                                         @"num":[NSString stringWithFormat:@"%ld",productInfo.nums]
                                         };
                [self SetUpShopCarEditNumber:params];
            }
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [progressHUD hide:YES];
                    CarConfirmOrderController *confirm = [[CarConfirmOrderController alloc] init];
                    confirm.productArray = self.selectGoods;
                    confirm.allPrice = priceLabel.text;
                    [self.navigationController pushForm:self.navigationController pushToAndHidden:confirm];
                });
            });
        }
    });
    
}

- (void)didClickDeleteButton:(UIButton *)deleteButton {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定删除该商品" preferredStyle:UIAlertControllerStyleAlert];
    
    __weak typeof(self) weakSelf = self;
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            progressHUD = [MBProgressHUD loadingInformationToView];
            [weakSelf.view addSubview:progressHUD];
        });
        
        ProductInfo *model = self.productsArray[deleteButton.tag];
        NSLog(@"%@",model);
        [weakSelf deleteDatasources:model.id];
    }];
    [alert addAction:deleteAction];
    
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark>>>>>>>>DataSource
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 6;
}


- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    homeCollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:firstReuseIdentifier forIndexPath:indexPath];
    
    cell.productImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"custom%ld.jpg",indexPath.item]];
    cell.productImage.contentMode = UIViewContentModeScaleToFill;
    
    cell.productName.text = @"2016春夏装韩流风顶级美女高俊熙小姐";
    cell.price.text = @"专享价: 180元";
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
    
    return cell;
    
}

//header组头大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    //头部视图size
    return CGSizeMake(WIDTH,HEIGHT/3);
    
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    return CGSizeMake(WIDTH/2-MAR_WIDTH/2-5, HEIGHT/2.8);
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0,MAR_WIDTH,0,MAR_WIDTH);
}


-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *reusableView;
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) { //
        
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"shopCarHeader" forIndexPath:indexPath];
        shopCarHeaderView *headerView = [[shopCarHeaderView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/3)];
        headerView.delegate = self;
        [reusableView addSubview:headerView];
        return reusableView;
    }
    return  nil;
}

- (void)shopCarHeaderButtonDidClick:(UIButton *)button
{
    NSLog(@"%ld",button.tag);
    
}

#pragma mark TableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.productsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [progressHUD hide:YES];
    [progressHUD removeFromSuperview];
    
    __block ShopCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    
    if (!cell) {
        cell = [[ShopCarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    cell.leftButton.tag = indexPath.row;
    
    leftButton = cell.leftButton;
    
    cell.delegate = self;
    
    cell.deleteButton.tag = indexPath.row;
    
    cell.isSelected = isSelect;
    
    //是否被选中
    if ([_selectGoods containsObject:[self.productsArray objectAtIndex:indexPath.row]]) {
        cell.isSelected = YES;
    }
    
    //选择回调
    cell.cartBlock = ^(BOOL isSelec){
        
        if (isSelec) {
            //            ProductInfo *dict = [self.productsArray objectAtIndex:indexPath.row];
            //            [dict setValue:@(indexPath.row) forKey:@"selectedIndex"];
            [_selectGoods addObject:[self.productsArray objectAtIndex:indexPath.row]];
            [self.selectedButton addObject:leftButton];
        }
        else
        {
            [_selectGoods removeObject:[self.productsArray objectAtIndex:indexPath.row]];
            [self.selectedButton removeObject:leftButton];
        }
        
        if (_selectGoods.count == self.productsArray.count) {
            selectAll.selected = YES;
        }
        else
        {
            selectAll.selected = NO;
        }
        
        [self countPrice];
    };
    __block ShopCarTableViewCell *weakCell = cell;
    cell.numAddBlock =^(){
        
        NSInteger count = [weakCell.numberLabel.text integerValue];
        count++;
        NSString *numStr = [NSString stringWithFormat:@"%ld",(long)count];
        
        ProductInfo *model = [self.productsArray objectAtIndex:indexPath.row];
        
        weakCell.numberLabel.text = numStr;
        model.nums = count;
        
        [self.productsArray replaceObjectAtIndex:indexPath.row withObject:model];
        if ([_selectGoods containsObject:model]) {
            [_selectGoods removeObject:model];
            [_selectGoods addObject:model];
            [self countPrice];
        }
    };
    
    cell.numCutBlock =^(){
        
        NSInteger count = [weakCell.numberLabel.text integerValue];
        count--;
        if(count <= 0){
            return ;
        }
        NSString *numStr = [NSString stringWithFormat:@"%ld",(long)count];
        
        ProductInfo *model = [self.productsArray objectAtIndex:indexPath.row];
        
        weakCell.numberLabel.text = numStr;
        
        model.nums = count;
        [self.productsArray replaceObjectAtIndex:indexPath.row withObject:model];
        
        //判断已选择数组里有无该对象,有就删除  重新添加
        if ([_selectGoods containsObject:model]) {
            [_selectGoods removeObject:model];
            [_selectGoods addObject:model];
            [self countPrice];
        }
    };
    
    [cell reloadDataWith:[self.productsArray objectAtIndex:indexPath.row]];
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 106;
}

- (NSMutableArray *)productsArray {
    if (!_productsArray) {
        _productsArray = [NSMutableArray array];
    }
    return _productsArray;
}

- (NSMutableArray *)selectedButton {
    if (!_selectedButton) {
        _selectedButton = [NSMutableArray array];
    }
    return _selectedButton;
}

- (NSMutableArray *)selectGoods {
    if (!_selectGoods) {
        _selectGoods = [NSMutableArray array];
    }
    return _selectGoods;
}

@end
